#include	"XmlParser.hpp"
#include	"tinyxml.h"

using namespace std;

XmlParser::XmlParser()
{
	this->_File = "";
}

XmlParser::XmlParser(const std::string &file)
{
	this->_File = file;
}

XmlParser::~XmlParser()
{
}

int							XmlParser::parseFile()
{
	int		ret = -2;

	if (this->getFile().size() != 0)
	{
		TiXmlDocument		doc("conf.xml");

		if (!doc.LoadFile())
			ret = -1;
		else
		{
			try
			{
				TiXmlElement *elem = doc.FirstChildElement();
				ret = 1;
				if ((elem->Value() != NULL) && (strcmp(elem->Value(), "Module") == 0))
				{
					TiXmlElement *child = elem->FirstChildElement();
					if (child && !strcmp(child->Value(), "PHP") && child->Attribute("state"))
					{
						cout << "Child1: " << child->Attribute("state") << endl;
						if (child->Attribute("state") == "ENABLE" || child->Attribute("state") == "DISABLE")
							cout << "Child2: " << child->Attribute("state") << endl;
						else
							throw("for state's field, only ENABLE or DISABLE values are accepted");
						child = child->NextSiblingElement();
						if (child && !strcmp(child->Value(), "SSL") && child->Attribute("state"))
						{
							if (child->Attribute("state") == "ENABLE" || child->Attribute("state") == "DISABLE")
								cout << "Child2: " << child->Attribute("state") << endl;
							else
								throw("for state's field, only ENABLE or DISABLE values are accepted");
						}
						else
							throw("SSL should be after PHP");
					}
					else
						throw("PHP should be the first child of Module");
				}
				else
					throw("<Module> wasn't found, or isn't the root node");
			}
			catch (const char * err)
			{
				cerr << "An error has occured: " << err << endl;
				cerr << "Regenerating conf file with default values" << endl;
				cerr << "Done" << endl;
			}
			catch (...)
			{
				cerr << "Unknown Error has occured" << endl;
				cerr << "Regenerating conf file with default values" << endl;
				cerr << "Done" << endl;
			}
		}
	}
	return (ret);
}

void						XmlParser::setFile(const std::string &file)
{
	this->_File = file;
	return ;
}

const std::string &			XmlParser::getFile()
{
	return (this->_File);
}